package com.mapperdb.spring;

import static org.springframework.util.Assert.notNull;

import org.apache.ibatis.executor.ErrorContext;
import org.mybatis.spring.mapper.MapperFactoryBean;

import com.mapperdb.binding.MapperRegistryProxy;

public class MapperFactoryBeanSupprot<T> extends MapperFactoryBean<T> {

	private Class<T> mapperInterface;

	private boolean addToConfig = true;

	private MapperRegistryProxy mapperRegistryProxy;

	public void setMapperRegistryProxy(MapperRegistryProxy mapperRegistryProxy) {
		this.mapperRegistryProxy = mapperRegistryProxy;
	}

	public void setMapperInterface(Class<T> mapperInterface) {
		super.setMapperInterface(mapperInterface);
		this.mapperInterface = mapperInterface;
	}

	public void setAddToConfig(boolean addToConfig) {
		super.setAddToConfig(addToConfig);
		this.addToConfig = addToConfig;
	}

	@Override
	protected void checkDaoConfig() {
		notNull(getSqlSession(), "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
		notNull(this.mapperInterface, "Property 'mapperInterface' is required");
		
		mapperRegistryProxy.setConfiguration(getSqlSession().getConfiguration());
		
		if (this.addToConfig && !mapperRegistryProxy.hasMapper(this.mapperInterface)) {
			try {
				mapperRegistryProxy.addMapper(this.mapperInterface);
			} catch (Throwable t) {
				logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", t);
				throw new IllegalArgumentException(t);
			} finally {
				ErrorContext.instance().reset();
			}
		}
	}
}
